package com.example.demo.component;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.concurrent.ConcurrentHashMap;
//通过这个类来记录当前用户在线的状态，维护userId和WebSocketSession之间的映射
@Component
public class OnlineUserManager {
    //hashMap要考虑线程安全问题
    private ConcurrentHashMap<Integer, WebSocketSession> sessions=new ConcurrentHashMap<>();
    public void online(int userId,WebSocketSession session) {
        //1.用户上线，给哈希表插入键值对
        if (sessions.get(userId) != null) {
            //已经上线了，就登陆失败（防止多开）
            System.out.println("[" + userId + "]已经登录了！");
            return;
        }
        sessions.put(userId, session);
        System.out.println("[" + userId + "]上线");
    }
        //2.用户下线，针对这个hash表进行元素删除
    public void offline(int userId,WebSocketSession session){
        WebSocketSession existSession = sessions.get(userId);
        if(existSession == session){
            sessions.remove(userId);
            System.out.println("[" + userId + "]下线");

        }
    }
        //3.根据userId获取到WebSocketSession
    public WebSocketSession getSession(int userId){
        return sessions.get(userId);
    }


}
